﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using System.Runtime.Serialization;
namespace Sistema.Dominio
{
    [DataContract]
    public abstract class EntidadeValidavel<T> : Entidade, IDataErrorInfo
    {
        protected ValidationResults _validationResults;
        private bool _eValido;

        protected EntidadeValidavel()
        {
            UpdateValidationState();
        }

        protected void UpdateValidationState()
        {
            Validator<T> validator = ValidationFactory.CreateValidator<T>();
            _validationResults = validator.Validate(this);
            this.EValido = _validationResults.IsValid;
        }

        public bool EValido
        {
            get { return _eValido; }
            set { _eValido = value; base.RaisePropertyChanged("EValido"); }
        }

        protected override void RaisePropertyChanged(string propertyname)
        {
            base.RaisePropertyChanged(propertyname);
            UpdateValidationState();
        }

        #region IDataErrorInfo Members

        public string Error
        {
            get 
            {
                IList<String> asd = (from ValidationResult x in _validationResults.ToList()
                                    select x.Message).ToList();
                return String.Join(Environment.NewLine,asd.ToArray());
            }
        }

        public string this[string columnName]
        {
            get
            {
                string message = null;
                var filteredResult = new ValidationResults();

                var result = _validationResults.FirstOrDefault(x => x.Key == columnName);
                if (result != null)
                {
                    filteredResult.AddResult(result);
                    message = filteredResult.First().Message;
                }
                return message;
            }
        }

        #endregion
    }
}
